import queue
import random
import threading
import socket

from 聊天软件.ReceiveTask import ReceiveTask

'''
实现功能：
（1）私人聊天
'''
messages=queue.Queue #(addr,message)
users=[] #[(username,clientscoket)]
username = random.choices(range(1000))
class ChatServer(threading.Thread):
    IP = socket.gethostbyname(socket.gethostname())
    PORT = 9999

    def __init__(self):
        threading.Thread.__init__(self)
        #  创建socket
        self.socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

    def run(self):
        # 绑定地址和端口，开始监听服务
        self.socket.bind((self.IP, self.PORT))
        self.socket.listen(5)
        # 转发消息服务
        q = threading.Thread(target=self.send(), name="Thread-send")
        q.start()
        # 客户端连接服务端时，启动线程作为保存客户端socket
        while True:
            clientsocket, addr = self.socket.accept()
            t = threading.Thread(target=self.receive(clientsocket, addr), name="Thread-saveclient")
            t.start()
            # receiveTask = ReceiveTask(clientsocket,addr)
            # receiveTask.start()

    # 客户端连接服务端时，启动线程作为保存客户端socket
    def receive(self, clientsocket, addr):
        clientsocket.recv(1024)
        users.append((username,clientsocket))
        print("用户{0}有加入聊天".format(addr))
        # 接收来自客户端的消息
        try:
            while True:
                clientmsg = clientsocket.recv(1024)
                clientmsg = clientmsg.decode("utf-8")
                messages.put((addr,clientmsg))
                print("{0} >>> {1}".format(addr, clientmsg))
        except:
            print("{0}用户已经退出!".format(addr))
            clientsocket.close()
            users.remove((username,clientsocket))

    # 将messages队列里的消息转发到客户端
    def send(self):
        while True:
            if not messages.empty():
                messageTuple = messages.get()
                addr = messageTuple[0]
                message = ''+messageTuple[1]
                for usertuple in users:
                    name = usertuple[0]
                    clientsocket = usertuple[1]
                    if(name != username):
                        try:
                            clientsocket.send(message.encode("utf-8"))
                            print("{0} >>> {1}".format(name, message))
                        except:
                            print("{0}用户有退出！")

if __name__ == '__main__':
    server = ChatServer()
    server.start()





